


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>layuiAdmin 网站用户 iframe 框</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <link rel="stylesheet" href="../layui/css/layui.css" media="all">
</head>
<style>
  .layui-form-select{
    width:200px
  }
  .layui-select-title{
    width:200px
  }
  .layui-input{
    width: 200px;
  }
  
</style>
<body>

<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list" style="padding: 20px 30px 0 0;">
  <div class="layui-form-item">
    <label class="layui-form-label">文章标题</label>
    <div class="layui-input-inline">
      <input type="text" name="title" lay-verify="required" placeholder="请输入文章标题" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">发布人ID</label>
    <div class="layui-input-inline">
      <input type="text" name="userId" lay-verify="required" placeholder="请输入发布人ID" autocomplete="off" class="layui-input">
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">文章内容</label>
    <div class="layui-input-inline">
      <textarea name="content" lay-verify="required" style="width: 400px; height: 150px;" autocomplete="off" class="layui-textarea"></textarea>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">文章标签</label>
    <div class="layui-input-inline">
      <select name="categoryId" lay-verify="required">
        
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">发布状态</label>
    <div class="layui-input-inline">
      <select name="status" lay-verify="required">
        <option value="0">草稿</option>
        <option value="1">待审核</option>
        <option value="2">已发布</option>
        <option value="3">未通过</option>
      </select>
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">文章附件</label>
    <div class="layui-input-inline">
      <input type="text" name="attachment" lay-verify="required"
             placeholder="请上传文件" autocomplete="off" class="layui-input">
    </div>
    <button type="button" class="layui-btn" id="test3"><i class="layui-icon"></i>上传文件</button>
    <div class="layui-form-item" id="attachmentPreview" style="margin-left: 110px; display: none;">
      <div class="layui-form-mid">附件预览：</div>
      <div id="filePreviewContent"></div>
    </div>
    </div>

  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">文章视频</label>
    <div class="layui-input-inline">
      <input type="text" name="video" lay-verify="required"
             placeholder="请上传视频" autocomplete="off" class="layui-input">
    </div>
    <button type="button" class="layui-btn" id="test5"><i class="layui-icon"></i>上传视频</button>
    <!-- 视频预览区域 -->
    <div class="layui-form-item" id="videoPreview" style="margin-left: 110px; display: none;">
      <div class="layui-form-mid">视频预览：</div>
      <div id="videoPreviewContent"></div>
    </div>
  </div>
</div>
<script src="./JS/utils/request.js"></script>
  <script src="./JS/utils/auth.js"></script>
  <script src="../layui/layui.all.js"></script>  
  <script>
 layui.laydate.render({
  elem: '#date'
});

 // 根据URL获取文件类型
 function getFileType(url) {
   const ext = url.split('.').pop().toLowerCase();
   const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
   const videoTypes = ['mp4', 'avi', 'mov', 'wmv'];
   const docTypes = ['pdf', 'doc', 'docx', 'xls', 'ppt'];

   if (imageTypes.includes(ext)) return 'image';
   if (videoTypes.includes(ext)) return 'video';
   if (docTypes.includes(ext)) return 'document';
   return 'other';
 }

layui.use(['form', 'jquery','upload'], function(){
            let form = layui.form;
            let $ = layui.$;
            let upload = layui.upload

            // 获取文章标签下拉菜单的动态请求列表
      $.ajax({
        url: '/articles/getCategories', // 替换为实际接口地址
        type: 'GET',
        headers:{
              'Authorization':localStorage.getItem('token')
    },
        success: function(res) {
          console.log(res)
          if (res.code === 0) { // 根据实际接口返回状态码调整
            var selectHtml = '';

            // 遍历返回数据生成option
            res.data.forEach(function(item) {
              selectHtml += '<option value="' + item.categoryId + '">' + item.categoryName + '</option>';
            });

            // 更新select内容
            $('select[name="categoryId"]').html(selectHtml);

            // 重新渲染表单
            form.render('select');
          }
        },
        error: function(xhr, status, error) {
          console.error('分类数据获取失败:', error);
        }
      });


            // 定义提交方法供父页面调用
            window.submitForm = function(callback) {
                // 表单验证
                form.verify();
                
                // 获取表单数据
                let formData = {
                    title: $('input[name="title"]').val(),
                    userId:$('input[name="userId"]').val(),
                    content:$('textarea[name="content"]').val(),
                    categoryId:$('select[name="categoryId"]').val(),
                    status:$('select[name="status"]').val(),
                    attachment:$('input[name="attachment"]').val(),
                    video: $('input[name="video"]').val(),
                    
                };

                console.log(formData);
                
                // 发送AJAX请求
                $.ajax({
                    url: '/articles/insert',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(formData),
                    headers:{
              'Authorization':localStorage.getItem('token')
    },
                    success: function(res){
                      console.log(res)
                        if(res.code === 0){
                            callback(true);
                        } else {
                            layer.msg(res.msg || '提交失败');
                            callback(false);
                        }
                    },
                    error: function(xhr){
                        layer.msg('请求失败: 发布人ID不存在，请先注册用户！');
                        callback(false);
                    }
                });
            };

            //文件附件上传
            upload.render({
              elem: '#test3'
              ,url: '/articles/attachmentUpload' //此处配置你自己的上传接口即可
              ,accept: 'file' ,//普通文件
              headers:{
              'Authorization':localStorage.getItem('token')
    }
              ,done: function(res){
                // console.log(res)
            if(res.code === 0) {
              const fileUrl = res.data;
              const fileType = getFileType(fileUrl);

              // 显示预览区域
              $('#attachmentPreview').show();

              let previewHtml = '';
              switch(fileType) {
                case 'image':
                  previewHtml = `<img src="${fileUrl}" style="max-width: 200px; margin: 10px 0; border: 1px solid #eee;">`;
                  break;
                case 'video':
                  previewHtml = `
            <div style="margin: 10px 0;">
              <i class="layui-icon layui-icon-file" style="font-size: 20px;"></i>
              <a href="${fileUrl}" target="_blank" download
                 style="margin-left: 5px;">下载视频</a>
            </div>`;
                  break;
                case 'document':
                  previewHtml = `
            <div style="margin: 10px 0;">
              <i class="layui-icon layui-icon-file" style="font-size: 20px;"></i>
              <a href="${fileUrl}" target="_blank" download
                 style="margin-left: 5px;">下载文档</a>
            </div>`;
                  break;
                default:
                  previewHtml = `
            <div style="margin: 10px 0;">
              <a href="${fileUrl}" target="_blank" download
                 class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-download"></i> 下载文件
              </a>
            </div>`;
              }

              $('#filePreviewContent').html(previewHtml);
              $('input[name="attachment"]').val(fileUrl);

                  layer.msg('上传成功');
                  // // 预览图片
                  // $('#avatarPreview').html(
                  //         `<img src="${res.data}" style="max-width: 100px; margin-top: 10px;">`
                  // );
                  $('input[name="attachment"]').val(res.data)
                } else {
                  layer.msg(res.msg || '上传失败');
                }
          },
          error: function(){
                layer.msg('上传失败，文件最大不超过100MB');
              }
            });

          //视频附件上传
          upload.render({
          elem: '#test5'
          ,url: '/articles/attachmentUpload' //此处配置你自己的上传接口即可
          ,accept: 'video', //视频
          headers:{
              'Authorization':localStorage.getItem('token')
    }
          ,done: function(res){
            // console.log(res)
            if(res.code === 0) {
              const fileUrl = res.data;
              const fileType = getFileType(fileUrl);

              // 显示预览区域
              $('#videoPreview').show();

              let previewHtml = '';
              switch(fileType) {
                case 'image':
                  previewHtml = `<img src="${fileUrl}" style="max-width: 200px; margin: 10px 0; border: 1px solid #eee;">`;
                  break;
                case 'video':
                  previewHtml = `
            <div style="margin: 10px 0;">
              <i class="layui-icon layui-icon-file" style="font-size: 20px;"></i>
              <a href="${fileUrl}" target="_blank" download
                 style="margin-left: 5px;">下载视频</a>
            </div>`;
                  break;
                case 'document':
                  previewHtml = `
            <div style="margin: 10px 0;">
              <i class="layui-icon layui-icon-file" style="font-size: 20px;"></i>
              <a href="${fileUrl}" target="_blank" download
                 style="margin-left: 5px;">下载文档</a>
            </div>`;
                  break;
                default:
                  previewHtml = `
            <div style="margin: 10px 0;">
              <a href="${fileUrl}" target="_blank" download
                 class="layui-btn layui-btn-primary layui-btn-sm">
                <i class="layui-icon layui-icon-download"></i> 下载文件
              </a>
            </div>`;
              }

              $('#videoPreviewContent').html(previewHtml);
              $('input[name="video"]').val(fileUrl);

                  layer.msg('上传成功');
                  // 预览图片
                  // $('#avatarPreview').html(
                  //         `<img src="${res.data}" style="max-width: 100px; margin-top: 10px;">`
                  // );
                  $('input[name="video"]').val(res.data)
                } else {
                  layer.msg(res.msg || '上传失败');
                }
          },
          error: function(){
                layer.msg('上传失败，视频最大不超过100MB');
              }
        });

          

            // 暴露初始化方法供父页面调用用于编辑信息时的数据回显
            window.initFormData = function(data){
              // 填充表单数据
              form.val('layuiadmin-app-form-list', {
                "title": data.title,
                "userId": data.userId,
                "content": data.content,
                "categoryId":data.categoryId,
                "status":data.status,
                "attachment":data.attachment,
                "video":data.video,
              });
              // 预览图片
              $('input[name="attachment"]').val(data.attachment)
              $('input[name="video"]').val(data.video)
              // 重新渲染表单
              form.render();
            };


        //     保存更改后的表单数据
        // 定义提交方法供父页面调用
        window.updateForm = function(callback) {
          // 表单验证
          form.verify();
          //获取index.html文件发送的articleId的值
          const urlParams = new URLSearchParams(window.location.search);
          console.log(urlParams)
          const articleId = urlParams.get('articleId');
          console.log(articleId)
           // 获取表单数据
           let formData = {
                    title: $('input[name="title"]').val(),
                    userId:$('select[name="userId"]').val(),
                    content:$('textarea[name="content"]').val(),
                    categoryId:$('select[name="categoryId"]').val(),
                    status:$('select[name="status"]').val(),
                    attachment:$('input[name="attachment"]').val(),
                    video: $('input[name="video"]').val(),
                    articleId:articleId
                };

          console.log(formData);

          // 发送AJAX请求
          $.ajax({
            url: '/articles/update',
            method: 'PUT',
            contentType: 'application/json',
            data: JSON.stringify(formData),
            headers:{
              'Authorization':localStorage.getItem('token')
    },
            success: function(res){
              console.log(res)
              if(res.code === 0){
                callback(true);
              } else {
                layer.msg(res.msg || '更新失败');
                callback(false);
              }
            },
            error: function(xhr){
              layer.msg('请求失败:' + xhr.statusText);
              callback(false);
            }
          });
        };


        });
  </script>
</body>
</html>